package com.imooc.ecommerce.advice;

import com.imooc.ecommerce.exception.BizException;
import com.imooc.ecommerce.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕获处理
 *
 * @Author: zhangshao
 * @Date: 2023/3/23 12:36
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 捕获BizException 进行统一异常处理
     *
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    public CommonResponse<Void> bizExceptionHandler(HttpServletRequest request, BizException ex) {
        log.error("has some error in request :[{}], ErrorCode:[{}],errorMsg: [{}]",
                request.getRequestURI(), ex.getErrorCode(), ex.getErrorMessage());

        return new CommonResponse<>(Integer.valueOf(ex.getErrorCode()),ex.getErrorMessage());

    }

    /**
     * 兜底策略
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public CommonResponse<String> handleCommerceException(HttpServletRequest request, Exception ex) {
        CommonResponse<String> response = new CommonResponse<>(-1, "business error");
        response.setData(ex.getMessage());
        log.error("commerce service has error: [{}]", ex.getMessage(), ex);
        return response;
    }
}
